import {router} from "../router"
import {MethodType} from "../types";
import {RequestHandler} from "express";

type MyClassDecorator = <T extends { new(...args: any): any }>(targetClass: T) => any

export function Controller(reqRootPath: string): MyClassDecorator {
    return function (targetClass): any {
        console.log("执行控制器装饰器：执行的类是==>", targetClass);

        //遍历控制器上所有的方法
        for (let methodname in targetClass.prototype) {
            // 获取对应的方法
            const targetMethodfunc = targetClass.prototype[methodname];

            // 获取方法装饰器中保存的元数据
            let reqPath = Reflect.getMetadata("path", targetClass.prototype, methodname);
            let methodType: MethodType = Reflect.getMetadata("methodType", targetClass.prototype, methodname);
            let middlewares: RequestHandler[] = Reflect.getMetadata("middlewares", targetClass.prototype, methodname);

            // 路由映射。S100理解：当执行对应routePath时，会自动执行targetMethodfunc方法
            if (reqPath && methodType) {
                const routePath = `${reqRootPath.replace(/\/$/, "")}/${reqPath.replace(/^\//, "")}`;
                if (middlewares) {
                    router[methodType](routePath, ...middlewares, targetMethodfunc); // 有中间件先执行中间件
                } else {
                    router[methodType](routePath, targetMethodfunc); // S100
                }
            }
        }
    }
}
